package com.interf.wms;

import com.yy.base.common.dialect.MapResult;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
public class DBUtil {
	/**
	 * 查询数据
	 * @param sql
	 * @param objs
	 * @return
	 */
	public static List<Map<String, Object>> query(String sql, Object... objs) {
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		PreparedStatement ps = null;
		ResultSet rs = null;
		Connection conn = null;
		try {
			conn = ConnectionPool.getConnection();
			ps = conn.prepareStatement(sql);
			if (objs != null && objs.length > 0) {
				for (int i = 1;i <= objs.length;i ++) {
					ps.setObject(i, objs[i - 1]);
				}
			}
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = ps.getMetaData();
			int size = rsmd.getColumnCount();
			String[] names = new String[size];
			for (int i = 1; i <= size; i++) {
				try {
					names[i - 1] = rsmd.getColumnName(i);
				} catch (Exception e) {
				}
			}
			
			Map<String, Object> map = null;
			while (rs.next()) {
				map = new MapResult();
				for (int i = 0; i < names.length; i++) {
					map.put(names[i].toUpperCase(), rs.getObject(names[i]));
				}
				list.add(map);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				rs.close();
			} catch (Exception e) {
			}
			try {
				ps.close();
			} catch (Exception e) {
			}
			try {
				conn.close();
			} catch (Exception e) {
			}
		}
		return list;
	}

	public static Map<String, Object> queryUnique(String sql, Object... objs) {
		List<Map<String, Object>> list = query(sql, objs);
		if (list != null && !list.isEmpty()) {
			return list.get(0);
		}
		return null;
	}
	/**
	 * 执行SQL语句
	 * @param sql
	 * @param objs
	 * @return
	 */
	@SuppressWarnings("null")
	public static int execute(String sql, Object... objs) {
		PreparedStatement ps = null;
		ResultSet rs = null;
		Connection conn = null;
		try {
			conn = ConnectionPool.getConnection();
			ps = conn.prepareStatement(sql);
			if (objs != null && objs.length > 0) {
				for (int i = 0;i < objs.length;i ++) {
					ps.setObject(i+1, objs[i]);
				}
			}
			return ps.executeUpdate();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				rs.close();
			} catch (Exception e) {
			}
			try {
				ps.close();
			} catch (Exception e) {
			}
			try {
				conn.close();
			} catch (Exception e) {
			}
		}
	}
}